<template>
  <div class="place-approval">
    <div class="page-header">
      <h2>场地申请审批</h2>
      <p>管理场地使用申请，审批通过后场地将分配给相应活动</p>
    </div>

    <div class="content-card">
      <!-- 搜索和筛选区域 -->
      <div class="filter-bar">
        <div class="search-box">
          <input
            type="text"
            v-model="searchKeyword"
            placeholder="搜索申请ID、场地ID或申请备注..."
            @keyup.enter="fetchApplications"
            class="search-input"
          >
          <button @click="fetchApplications" class="search-btn">
            <span class="icon">🔍</span>
            搜索
          </button>
        </div>

        <div class="filter-group">
          <select v-model="statusFilter" @change="fetchApplications" class="status-select">
            <option value="">全部状态</option>
            <option value="0">待审核</option>
            <option value="1">已通过</option>
            <option value="2">已取消</option>
          </select>
        </div>
      </div>

      <!-- 申请列表 -->
      <div class="applications-list">
        <div v-if="loading" class="loading-state">
          <div class="loading-spinner"></div>
          <p>加载申请列表中...</p>
        </div>

        <div v-else-if="error" class="error-state">
          <div class="error-icon">⚠️</div>
          <p>{{ error }}</p>
          <button @click="fetchApplications" class="retry-btn">重新加载</button>
        </div>

        <div v-else-if="applications.length === 0" class="empty-state">
          <div class="empty-icon">🏟️</div>
          <p>暂无场地申请</p>
        </div>

        <div v-else class="applications-table">
          <table class="applications-table">
            <thead>
              <tr>
                <th>申请ID</th>
                <th>主办方ID</th>
                <th>场地ID</th>
                <th>申请时间</th>
                <th>使用时间</th>
                <th>申请备注</th>
                <th>状态</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="app in filteredApplications"
                :key="app.leaId"
                :class="getStatusRowClass(app.leaStatus)"
              >
                <td>{{ app.leaId }}</td>
                <td>{{ app.orId }}</td>
                <td>{{ app.plId }}</td>
                <td>{{ formatDateTime(app.appTime) }}</td>
                <td>
                  {{ formatDate(app.startDate) }} 至
                  {{ formatDate(app.endDate) }}
                </td>
                <td class="remark-cell">{{ app.leaRemark || '无备注' }}</td>
                <td>
                  <span class="status-badge" :class="getStatusBadgeClass(app.leaStatus)">
                    {{ getStatusText(app.leaStatus) }}
                  </span>
                </td>
                <td>
                  <div class="action-buttons" v-if="app.leaStatus === 0">
                    <button
                      @click="handleApprove(app)"
                      class="btn-approve"
                      :disabled="processingApp === app.leaId"
                    >
                      {{ processingApp === app.leaId ? '处理中...' : '通过' }}
                    </button>
                    <button
                      @click="showRejectDialog(app)"
                      class="btn-reject"
                      :disabled="processingApp === app.leaId"
                    >
                      驳回
                    </button>
                  </div>
                  <div v-else-if="app.leaStatus === 1" class="approved-info">
                    <span class="approval-opinion" v-if="app.maOpinion">
                      意见: {{ app.maOpinion }}
                    </span>
                    <span v-else class="no-actions">已通过</span>
                  </div>
                  <span v-else class="no-actions">-</span>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- 驳回申请弹窗 -->
    <div v-if="showRejectModal" class="modal-backdrop" @click.self="closeRejectModal">
      <div class="modal">
        <div class="modal-header">
          <h3>驳回场地申请</h3>
          <button @click="closeRejectModal" class="close-btn">×</button>
        </div>
        <div class="modal-body">
          <p>确定要驳回该场地申请吗？请填写驳回理由：</p>
          <textarea
            v-model="rejectReason"
            placeholder="请输入驳回理由..."
            rows="4"
            class="reject-textarea"
          ></textarea>
        </div>
        <div class="modal-footer">
          <button @click="closeRejectModal" class="btn-cancel">取消</button>
          <button @click="handleReject" class="btn-confirm-reject">确认驳回</button>
        </div>
      </div>
    </div>

    <!-- 申请详情弹窗 -->
    <div v-if="showDetailModal" class="modal-backdrop" @click.self="closeDetailModal">
      <div class="modal detail-modal">
        <div class="modal-header">
          <h3>场地申请详情</h3>
          <button @click="closeDetailModal" class="close-btn">×</button>
        </div>
        <div class="modal-body" v-if="currentDetail">
          <div class="detail-section">
            <h4>基本信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">申请ID:</span>
                <span class="value">{{ currentDetail.leaId }}</span>
              </div>
              <div class="detail-item">
                <span class="label">主办方ID:</span>
                <span class="value">{{ currentDetail.orId }}</span>
              </div>
              <div class="detail-item">
                <span class="label">场地ID:</span>
                <span class="value">{{ currentDetail.plId }}</span>
              </div>
              <div class="detail-item">
                <span class="label">申请时间:</span>
                <span class="value">{{ formatDateTime(currentDetail.appTime) }}</span>
              </div>
              <div class="detail-item">
                <span class="label">使用时间:</span>
                <span class="value">
                  {{ formatDateTime(currentDetail.startDate) }} 至
                  {{ formatDateTime(currentDetail.endDate) }}
                </span>
              </div>
              <div class="detail-item">
                <span class="label">状态:</span>
                <span class="value">
                  <span :class="`status-badge ${getStatusBadgeClass(currentDetail.leaStatus)}`">
                    {{ getStatusText(currentDetail.leaStatus) }}
                  </span>
                </span>
              </div>
            </div>
          </div>

          <!-- 申请说明 -->
          <div class="detail-section">
            <h4>申请备注</h4>
            <div class="description-content">
              {{ currentDetail.leaRemark || '无备注' }}
            </div>
          </div>

          <!-- 审批信息 -->
          <div v-if="currentDetail.maOpinion" class="detail-section">
            <h4>审批信息</h4>
            <div class="detail-grid">
              <div class="detail-item">
                <span class="label">审批意见:</span>
                <span class="value">{{ currentDetail.maOpinion }}</span>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="closeDetailModal" class="btn-close">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'

// 定义场地申请数据类型 - 根据后端实际返回的JSON结构调整
interface PlaceApplication {
  leaId: number           // 申请ID
  orId: number            // 主办方ID
  plId: number            // 场地ID
  appTime: string         // 申请时间
  startDate: string       // 开始日期
  endDate: string         // 结束日期
  leaRemark: string       // 申请备注
  leaStatus: number       // 申请状态：0-待审核，1-已通过，2-已取消
  maOpinion?: string      // 管理员审核意见
}

// 审批请求参数类型
interface ApproveRequest {
  leaId: number
  leaStatus: number
  maOpinion: string
}
// 响应数据类型
interface ApiResponse {
  success: boolean
  msg?: string
  data?: PlaceApplication[]
}

// 状态管理
const applications = ref<PlaceApplication[]>([])
const loading = ref(false)
const error = ref('')
const searchKeyword = ref('')
const statusFilter = ref('')
const processingApp = ref<number | null>(null)
const showRejectModal = ref(false)
const rejectReason = ref('')
const currentApp = ref<PlaceApplication | null>(null)
const showDetailModal = ref(false)
const currentDetail = ref<PlaceApplication | null>(null)

// 计算属性：筛选后的申请列表
const filteredApplications = computed(() => {
  let filtered = applications.value

  // 状态筛选
  if (statusFilter.value !== '') {
    filtered = filtered.filter(app => app.leaStatus.toString() === statusFilter.value)
  }

  // 关键词搜索
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    filtered = filtered.filter(app =>
      app.leaId.toString().includes(keyword) ||
      app.plId.toString().includes(keyword) ||
      (app.leaRemark && app.leaRemark.toLowerCase().includes(keyword))
    )
  }

  return filtered
})

// 初始化加载
onMounted(() => {
  fetchApplications()
})

/**
 * 获取场地申请列表
 */
const fetchApplications = async () => {
  loading.value = true
  error.value = ''

  try {
    const token = localStorage.getItem('token')

    if (!token) {
      error.value = '未找到身份凭证，请重新登录'
      localStorage.removeItem('token')
      window.location.href = '/Login'
      return
    }

    const response = await fetch('http://localhost:8080/manager/getAllPlaceApplications', {
      method: 'GET',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      }
    })

    const result: ApiResponse = await response.json()

    if (result.success && result.data) {
      applications.value = result.data
    } else {
      error.value = result.msg || '获取场地申请列表失败'
      if (result.msg?.includes('未登录')) {
        localStorage.removeItem('token')
        window.location.href = '/Login'
      }
    }
  } catch (err) {
    console.error('获取场地申请列表失败:', err)
    error.value = '网络错误，请检查连接'
  } finally {
    loading.value = false
  }
}

/**
 * 通过申请
 */
const handleApprove = async (app: PlaceApplication) => {
  if (!app.leaId) return

  if (!confirm('确定要通过该场地申请吗？')) {
    return
  }

  processingApp.value = app.leaId

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      alert('未登录，请重新登录')
      window.location.href = '/Login'
      return
    }

    const response = await fetch('http://localhost:8080/manager/approvePlaceApplication', {
      method: 'POST',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        leaId: app.leaId,
        leaStatus: 1, // 已通过
        maOpinion: '申请已通过审核'
      } as ApproveRequest)
    })

    const result = await response.json()

    if (result.success) {
      alert('场地申请已通过')
      fetchApplications() // 刷新列表
    } else {
      alert(`操作失败: ${result.msg}`)
    }
  } catch (err) {
    console.error('审批操作失败:', err)
    alert('操作失败，请重试')
  } finally {
    processingApp.value = null
  }
}

/**
 * 驳回申请
 */
const handleReject = async () => {
  if (!currentApp.value?.leaId) return

  if (!rejectReason.value.trim()) {
    alert('请输入驳回理由')
    return
  }

  processingApp.value = currentApp.value.leaId

  try {
    const token = localStorage.getItem('token')
    if (!token) {
      alert('未登录，请重新登录')
      window.location.href = '/Login'
      return
    }

    const response = await fetch('http://localhost:8080/manager/approvePlaceApplication', {
      method: 'POST',
      headers: {
        'token': token,
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({
        leaId: currentApp.value.leaId,
        leaStatus: 2, // 已取消（驳回）
        maOpinion: rejectReason.value.trim()
      } as ApproveRequest)
    })

    const result = await response.json()

    if (result.success) {
      alert('场地申请已驳回')
      closeRejectModal()
      fetchApplications() // 刷新列表
    } else {
      alert(`操作失败: ${result.msg}`)
    }
  } catch (err) {
    console.error('驳回操作失败:', err)
    alert('操作失败，请重试')
  } finally {
    processingApp.value = null
  }
}

/**
 * 查看申请详情
 */
const showApplicationDetail = (app: PlaceApplication) => {
  currentDetail.value = app
  showDetailModal.value = true
}

/**
 * 关闭详情弹窗
 */
const closeDetailModal = () => {
  showDetailModal.value = false
  currentDetail.value = null
}
/**
 * 显示驳回弹窗
 */
const showRejectDialog = (app: PlaceApplication) => {
  console.log('显示驳回弹窗，申请ID:', app.leaId)
  currentApp.value = app
  rejectReason.value = ''
  showRejectModal.value = true
}

/**
 * 关闭驳回弹窗
 */
const closeRejectModal = () => {
  showRejectModal.value = false
  currentApp.value = null
  rejectReason.value = ''
}
/**
 * 获取状态文本
 */
const getStatusText = (status: number): string => {
  switch (status) {
    case 0: return '待审核'
    case 1: return '已通过'
    case 2: return '已取消'
    default: return '未知状态'
  }
}

/**
 * 获取状态徽章样式类
 */
const getStatusBadgeClass = (status: number): string => {
  switch (status) {
    case 0: return 'status-pending'
    case 1: return 'status-approved'
    case 2: return 'status-rejected'
    default: return 'status-unknown'
  }
}

/**
 * 获取表格行样式类
 */
const getStatusRowClass = (status: number): string => {
  switch (status) {
    case 0: return 'row-pending'
    case 1: return 'row-approved'
    case 2: return 'row-rejected'
    default: return ''
  }
}

/**
 * 格式化日期
 */
const formatDate = (dateString: string): string => {
  if (!dateString) return '未知时间'

  try {
    const date = new Date(dateString)
    return date.toLocaleDateString('zh-CN')
  } catch {
    return '无效日期'
  }
}

/**
 * 格式化日期时间
 */
const formatDateTime = (dateString: string): string => {
  if (!dateString) return '未知时间'

  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    })
  } catch {
    return '无效日期'
  }
}
</script>

<style scoped>
/* 在原有样式基础上添加以下样式 */
.remark-cell {
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.approved-info {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 4px;
}

.approval-opinion {
  font-size: 12px;
  color: #666;
  background: #f0f0f0;
  padding: 2px 6px;
  border-radius: 4px;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.place-approval {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.page-header {
  margin-bottom: 30px;
  text-align: center;
}

.page-header h2 {
  color: #2c3e50;
  margin-bottom: 8px;
  font-size: 2rem;
}

.page-header p {
  color: #666;
  font-size: 1.1rem;
}

.content-card {
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  padding: 24px;
}

/* 筛选栏样式 */
.filter-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
  flex-wrap: wrap;
  gap: 16px;
}

.search-box {
  display: flex;
  align-items: center;
  flex: 1;
  max-width: 400px;
}

.search-input {
  flex: 1;
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-right: none;
  border-radius: 8px 0 0 8px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s;
}

.search-input:focus {
  border-color: #3498db;
}

.search-btn {
  padding: 10px 20px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 0 8px 8px 0;
  cursor: pointer;
  transition: background-color 0.3s;
  display: flex;
  align-items: center;
  gap: 6px;
}

.search-btn:hover {
  background: #2980b9;
}

.status-select {
  padding: 10px 16px;
  border: 1px solid #ddd;
  border-radius: 8px;
  font-size: 14px;
  background: white;
  cursor: pointer;
}

/* 表格样式 */
.applications-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 16px;
}

.applications-table th,
.applications-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e0e0e0;
}

.applications-table th {
  background-color: #f8f9fa;
  font-weight: 600;
  color: #2c3e50;
}

.applications-table tr:hover {
  background-color: #f8f9fa;
}

.row-pending {
  background-color: #fff3cd;
}

.row-approved {
  background-color: #d4edda;
}

.row-rejected {
  background-color: #f8d7da;
}

/* 状态徽章 - 增加宽度和间距 */
.status-badge {
  padding: 6px 16px;  /* 增加内边距 */
  border-radius: 20px;
  font-size: 13px;    /* 稍微增大字体 */
  font-weight: 600;
  min-width: 70px;    /* 设置最小宽度 */
  text-align: center; /* 文字居中 */
  display: inline-block;
  box-sizing: border-box;
}

.status-pending {
  background: #fff3cd;
  color: #856404;
  border: 1px solid #ffeaa7;
}

.status-approved {
  background: #d1edff;
  color: #155724;
  border: 1px solid #a8e6cf;
}

.status-rejected {
  background: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}

/* 操作按钮也相应调整 */
.action-buttons {
  display: flex;
  gap: 10px; /* 增加按钮间距 */
}

.btn-approve, .btn-reject {
  padding: 8px 16px;  /* 增加按钮内边距 */
  border: none;
  border-radius: 6px; /* 稍微圆角 */
  cursor: pointer;
  font-size: 13px;
  font-weight: 500;
  min-width: 60px;    /* 设置按钮最小宽度 */
  text-align: center;
  transition: all 0.3s ease;
}

.btn-approve {
  background: #27ae60;
  color: white;
}

.btn-approve:hover:not(:disabled) {
  background: #219653;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(39, 174, 96, 0.3);
}

.btn-reject {
  background: #e74c3c;
  color: white;
}

.btn-reject:hover:not(:disabled) {
  background: #c0392b;
  transform: translateY(-1px);
  box-shadow: 0 2px 4px rgba(231, 76, 60, 0.3);
}

.btn-approve:disabled, .btn-reject:disabled {
  background: #bdc3c7;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}


/* 弹窗样式 */
.modal-backdrop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal {
  background: white;
  border-radius: 12px;
  padding: 0;
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow: hidden;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #e0e0e0;
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #f8f9fa;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #666;
}

.modal-body {
  padding: 20px;
}

.reject-textarea {
  width: 100%;
  padding: 12px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  resize: vertical;
  margin-top: 12px;
}

.reject-textarea:focus {
  outline: none;
  border-color: #3498db;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #e0e0e0;
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

.btn-cancel {
  padding: 8px 16px;
  background: #95a5a6;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.btn-cancel:hover {
  background: #7f8c8d;
}

.btn-confirm-reject {
  padding: 8px 16px;
  background: #e74c3c;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.btn-confirm-reject:hover {
  background: #c0392b;
}

/* 详情弹窗样式 */
.detail-modal {
  max-width: 600px;
}

.detail-section {
  margin-bottom: 24px;
}

.detail-section h4 {
  color: #2c3e50;
  margin-bottom: 12px;
  border-bottom: 1px solid #eee;
  padding-bottom: 8px;
}

.detail-grid {
  display: grid;
  gap: 12px;
}

.detail-item {
  display: flex;
  align-items: center;
}

.detail-item .label {
  font-weight: 600;
  color: #555;
  min-width: 100px;
  margin-right: 12px;
}

.detail-item .value {
  color: #333;
  flex: 1;
}

.description-content {
  background: #f8f9fa;
  padding: 16px;
  border-radius: 8px;
  border: 1px solid #e9ecef;
  line-height: 1.5;
}

.btn-close {
  padding: 10px 20px;
  background: #6c757d;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

.btn-close:hover {
  background: #5a6268;
}

/* 加载和空状态样式 */
.loading-state, .error-state, .empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 20px;
  text-align: center;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 3px solid #f3f3f3;
  border-top: 3px solid #3498db;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 16px;
}

.error-icon, .empty-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.retry-btn {
  margin-top: 16px;
  padding: 8px 16px;
  background: #3498db;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .place-approval {
    padding: 16px;
  }

  .filter-bar {
    flex-direction: column;
    align-items: stretch;
  }

  .search-box {
    max-width: none;
  }

  .applications-table {
    font-size: 14px;
  }

  .applications-table th,
  .applications-table td {
    padding: 8px 4px;
  }

  .action-buttons {
    flex-direction: column;
    gap: 4px;
  }
}
</style>
